﻿using System.IO;
using System.Reflection;
using System.Web.Hosting;
using TemplateFoundation.Reflection;

namespace TemplateFoundation.Gadgets
{
    /// <summary>
    /// Represents a single embedded resource as a file
    /// </summary>
    public class GadgetResourceVirtualFile : VirtualFile
    {
        private readonly string _path;
        private readonly AssemblyHelper _assemblyHelper;

        public GadgetResourceVirtualFile(string virtualPath, Assembly assembly) : base(string.Concat(GadgetVirtualPathProvider.VppPathPrefix, virtualPath))
        {
            _path = virtualPath.StartsWith("/")
                    ? virtualPath.Substring(1)
                    : virtualPath;

            _assemblyHelper = new AssemblyHelper(assembly);

            using (var stream = _assemblyHelper.Assembly.GetManifestResourceStream(string.Format("{0}.{1}", _assemblyHelper.AssemblyName, _path.Replace("/", "."))))
            {
                if (stream == null)
                {
                    return;
                }

                FileExists = true;
            }
        }

        public bool FileExists
        {
            get; protected set;
        }

        public override Stream Open()
        {
            var stream = _assemblyHelper.Assembly.GetManifestResourceStream(string.Format("{0}.{1}", _assemblyHelper.AssemblyName, _path.Replace("/", ".")));

            if (stream==null)
            {
                throw new GadgetException(string.Format("Unable to retrieve assembly resource stream for path '{0}'", _path));
            }

            return stream;
        }
    }

}